package com.xq.shop.controller.admin;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import com.google.gson.ExclusionStrategy;
import com.xq.shop.service.admin.IBaseService;
import com.xq.shop.util.GsonUtil;
import com.xq.shop.util.RespUtil;
import com.xq.shop.vo.RespMsg;
import com.xq.shop.vo.SearchObject;
import com.xq.shop.vo.RespMsg.Result;

public abstract class BaseController<T> {
	
	private Class<T> entityClass;
	
	@SuppressWarnings("unchecked")
	public BaseController() {
		
		Type genType = getClass().getGenericSuperclass();  
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
        entityClass = (Class) params[0];  
	}
	
	public String list(SearchObject search){
		
		return GsonUtil.toJson(getService().get(search));
	}
	
	public String list(SearchObject search, ExclusionStrategy strategy){
		
		return GsonUtil.toJson(getService().get(search), strategy);
	}
	
	public abstract IBaseService<T> getService();
	
	public ModelAndView edit(String id, ModelAndView view){
		
		T instance;
		if(id != null){
			instance = getService().get(Long.parseLong(id));
		} else {
			try {
				instance = entityClass.newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} finally {
				instance = null;
			}
		}
		
		if(instance == null){
			return view;
		} else {
			
			view.addObject("entity", instance);
			return view;
		}
	}
	
	public void delete(String id, HttpServletResponse response){
		
		RespMsg msg = new RespMsg();	//设置返回信息
		if(id != null && !"".equals(id.trim())){
			
			List<Long> id_List = new ArrayList<Long>();
			for (String str : id.trim().split(",")) {
				id_List.add(Long.valueOf(str)); // 将string转换为long类型
			}
			getService().delete(id_List);
			msg = new RespMsg(Result.success, "删除成功");
		} else {
			msg = new RespMsg(Result.error, "请选择数据");
		}
		RespUtil.renderJson(GsonUtil.toJson(msg), response);
	}
}
